package com.crm.customers.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.crm.base.controller.BaseController;
import com.crm.customers.model.ApproveItem;
import com.crm.customers.model.ApproveItemUser;
import com.crm.customers.model.Contract;
import com.crm.customers.model.ContractBill;
import com.crm.customers.model.ContractFiles;
import com.crm.customers.model.ContractMoneylog;
import com.crm.customers.model.ContractUpdateHistory;
import com.crm.customers.model.CustomerInfo;
import com.crm.customers.service.ApproveItemService;
import com.crm.customers.service.ContractBillService;
import com.crm.customers.service.ContractFilesService;
import com.crm.customers.service.ContractMoneylogService;
import com.crm.customers.service.ContractPerformanceService;
import com.crm.customers.service.ContractService;
import com.crm.customers.service.ContractUpdateHistoryService;
import com.crm.customers.service.CustomerService;
import com.crm.sys.model.FilesInfo;
import com.crm.sys.model.SysMessage;
import com.crm.sys.service.FilesInfoService;
import com.crm.sys.service.SysService;
import com.crm.user.model.UserInfo;
import com.crm.user.service.UserService;
import com.crm.util.Constants;
import com.crm.util.Pager;
import com.google.common.base.Strings;
import com.wjyup.coolq.util.CQSDK;

/**
 * 客户合同管理controller
 * */
@Controller
public class ContactsController extends BaseController {
	
	@Autowired
	private ContractService contractService;
	
	@Autowired
	private ContractMoneylogService contractMoneylogService;
	
	@Autowired
	private FilesInfoService filesInfoService;
	
	@Autowired
	private ContractFilesService contractFilesService;
	
	@Autowired
	private ContractBillService contractBillService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private ContractUpdateHistoryService contractUpdateHistoryService;
	@Autowired
	private ApproveItemService approveItemService;
	@Autowired
	private UserService userService;
	@Autowired
	private SysService sysService;
	@Autowired
	private ContractPerformanceService contractPerformanceService;
	
	
	/**
	 * 修改合同选择页面
	 * */
	@RequestMapping(value="/customer/contracttemplate")
	public String contactTemplate(@ModelAttribute Contract c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		CustomerInfo cinfo = customerService.getCustomerInfoById(c.getCusid());
		request.setAttribute("cusinfo", cinfo);
		return "customercontract/customercontracttemp"+cinfo.getType()+"-"+c.getType();
		
	}
	
	
	/**
	 * 合同详情
	 * @throws Exception 
	 * */
	@RequestMapping(value="/customer/contractinfo")
	public String contractInfo(@ModelAttribute Contract c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		Contract result = contractService.getContractInfo(c);
		
		/*
		 * 合同详情里面还有文件之类的，要查到了放到里面
		 * */
		//所以我要先知道合同的id
		Long contractid = result.getId();
		List<ContractFiles> fileList = contractFilesService.getFileIdByConid(contractid);
		result.setFileList(fileList);
		//然后还有人才证书合同列表
		Contract ca = new Contract();
		ca.setPid(contractid);
		List<Contract>  sublist = contractService.getAllContractListByPid(ca);
		for (Contract ct : sublist) {
			ct.setFileList(contractFilesService.getFileIdByConid(ct.getId()));
		}
		result.setSublist(sublist);
		request.setAttribute("info", result);
		return "customercontract/contractinfo";
	}
	
	/**
	 * 合同列表URL拼接
	 * @throws Exception 
	 * */
	@RequestMapping(value="/customer/contractlisturl",produces="text/html;charset=UTF-8")
	public String contractlisturl(@ModelAttribute Contract c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		String url = "/customer/intocontractlist";
		url += "p"+getSkipToPage();
		
		if (c.getSttime() != null) {
			url += "_st"+c.getSttime();
		}
		if (c.getEntime() != null) {
			url += "_et"+c.getEntime();
		}
		if (!Strings.isNullOrEmpty(c.getKeyWord())){
			url += "?kwd=" + URLEncoder.encode(URLEncoder.encode(c.getKeyWord(), "UTF-8"),"UTF-8");
		}
		return "redirect:" + url;
	}
	
	/**
	 * 进入合同列表页面
	 * @throws UnsupportedEncodingException 
	 * */
	@RequestMapping(value="/customer/intocontractlist{k}", produces="text/html;charset=UTF-8")
	public String intoContractList(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		Integer pageNo = 1;
		Integer pageSize = 10;
		String keyWord = null;
		
		Contract c = new Contract();
		
		if (k != null) {
			String key[] = k.split("_");
			for (String kk : key) {
				if (kk.indexOf("p") > -1) {
					pageNo = Integer.parseInt(kk.replace("p", ""));
				} else if (kk.indexOf("st") > -1) {
					c.setSttime(kk.replace("st", ""));
				} else if (kk.indexOf("et") > -1) {
					c.setEntime(kk.replace("et", ""));
				}
			}
		}
		
		if(request.getParameter("kwd")!=null){  
			keyWord = (URLDecoder.decode(URLDecoder.decode(request.getParameter("kwd"), "UTF-8"),"UTF-8"));
			c.setKeyWord(keyWord);
		}
		
		//所以是要获取所有我的合同
		Long uid = getLoginUser().getId();
		c.setUid(uid);
		List<Contract> conlist = contractService.getAllMyContractList(c, pageNo, pageSize);
		
		Pager pager = new Pager(pageNo, pageSize);
		pager.setResultList(conlist);
		pager.setUrl("/customer/intocontractlist"+k);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("KeyWord",keyWord);
		//params.put("Signingtime", c.getSigningtime());
		params.put("sttime", c.getSttime());
		params.put("entime", c.getEntime());
		pager.setParams(params);
		request.setAttribute("pager", pager);
		return "customercontract/contractlist";	
	}
	
	
	
	
	/**
	 * 进入合同列表页面
	 * @throws UnsupportedEncodingException 
	 * */
	@RequestMapping(value="/customer/managecontractlist", produces="text/html;charset=UTF-8")
	public String manageContractList(@ModelAttribute Contract c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		
		Long deptid = getLoginUser().getInfo().getDeptid();
		//获取部门下所有人
	    List<UserInfo> userlist = userService.getAllUserListByDeptId(deptid);
		request.setAttribute("userlist", userlist);
		
		//所以是要获取所有我的合同
		//Long uid = getLoginUser().getId();
		if(c.getUid()!=null&&c.getUid()<0) {
			c.setUid(null);
		} 
		//c.setPid(0L);
		List<Contract> conlist = contractService.getAllMyContractList(c, getSkipToPage(), pageSize);
		
		Pager pager = new Pager(getSkipToPage(), pageSize);
		pager.setResultList(conlist);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("KeyWord",c.getKeyWord());
		params.put("uid", c.getUid());
		//params.put("Signingtime", c.getSigningtime());
		params.put("sttime", c.getSttime());
		params.put("entime", c.getEntime());
		pager.setParams(params);
		request.setAttribute("pager", pager);
		return "customercontract/managecontractlist";	
	}
	
	
	/**
	 * 进入申请合同界面
	 * */
	/*@RequestMapping(value="/customer/intoapplyforcontract")
	public String intoApplyForContract(HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		return null;
	}*/
	
	/**
	 * 保存合同
	 * */
	@RequestMapping(value="/customer/savecontract", produces="text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String saveContract(@ModelAttribute Contract c,@RequestParam("cids") Long cids[],@RequestParam("totalms") Integer totalms[],
			@RequestParam("alonems") Integer alonems[],@RequestParam("uids") Long uids[],@RequestParam("otmoney") Integer otmoney[],@RequestParam("advancemoney") Integer advancemoney[],@RequestParam("titleremark") String remark[],@RequestParam("zsremark") String zsremark[], 
			HttpServletResponse response,HttpServletRequest request,RedirectAttributes redirectAttributes){
		
		
		//人才中的pid是对应企业的id
		int result = 0; //失败
		if(c!=null&&cids!=null&&totalms!=null&&uids!=null){
			c.setUid(getLoginUser().getId());
			c.setCreateuser(c.getUid());
			List<Contract>  sublist = new ArrayList();
			if(c.getContracttype()!=0) {
				int i = 0;
				for(Long cid:cids){
					Contract  newContract = new Contract();
					//当合同为挂靠合同时
					if(c.getContracttype()==1) {
						newContract.setUid(uids[i]);
					}else {
						newContract.setUid(getLoginUser().getId());
					}
					
					newContract.setCusid(cid);
					newContract.setSigningtime(c.getSigningtime());
					newContract.setLifetype(c.getLifetype());
					newContract.setTotalamount(totalms[i]);
					newContract.setAlonemoney(alonems[i]);
					newContract.setCreateuser(c.getUid());
					newContract.setAdvancemoney(advancemoney[i]);
					newContract.setContracttype(c.getContracttype());
					newContract.setOthermoney(otmoney[i]);
					if(c.getContracttype()==2&&remark!=null&&remark.length>0) {
						newContract.setRemark(remark[i]);
					}
					if(zsremark!=null&&zsremark.length>0) {
						newContract.setZsremark(zsremark[i]);
					} 
					sublist.add(newContract);
					//其他费用 新增一条人才合同
					if(newContract.getOthermoney()!=null&&newContract.getOthermoney()>0){
						Contract  newContractOne = new Contract();
						newContractOne.setUid(uids[i]);
						newContractOne.setCusid(cid);
						newContractOne.setSigningtime(c.getSigningtime());
						newContractOne.setLifetype(c.getLifetype());
						newContractOne.setTotalamount(otmoney[i]);
						newContractOne.setAlonemoney(otmoney[i]);
						newContractOne.setCreateuser(c.getUid());
						newContractOne.setContracttype(c.getContracttype());
						newContractOne.setOthermoney(0);
						newContractOne.setIsadditional(1);
						newContractOne.setZsremark("");
						sublist.add(newContractOne);
						
					}
					i++;
				}
			}
			 
			c.setSublist(sublist);
			contractService.saveContract(c);
			if(c.getId()!=null){
				result =1;//成功
			}
		} 
		return JSONArray.toJSONString(result);
	}
	
	/**
	 * 撤销合同
	 * 只有没有收款记录的合同才能被撤销
	 * */
	@RequestMapping(value="/customer/cancelcontract")
	@ResponseBody
	public String cancelContract(String id,String type,String pid,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		/*
		 * 要是type=0说明是个人 就看pid，是总合同id,根据总合同id查出所有的合同id然后设置成isdel
		 * 要是type=1说明是企业 就看id 根据总合同id查出所有合同id然后设置成isdel
		 * */
		Long ctid = null;
		Contract ct = new Contract();
		if (Integer.parseInt(type) == 0) {
			ctid = Long.parseLong(pid);
		} else {
			ctid = Long.parseLong(id);
		}
		//获取这个合同
		ct.setId(ctid);
		ct = contractService.getContractInfo(ct);
		//获取这个合同下的所有人才合同，并设置为已删除
		Contract sonct = new Contract();
		sonct.setPid(ctid);
		List<Contract> sonlist = contractService.getAllContractListByPid(sonct);
		for (Contract ctr : sonlist) {
			ctr.setIsdel(1);
			contractService.updateContract(ctr);
			ContractMoneylog cml = new ContractMoneylog();
			cml.setContractid(ctr.getId());
			contractMoneylogService.updateContractid(cml);
		}
		ct.setIsdel(1);
		contractService.updateContract(ct);
		//合同业绩也设置为删除
		contractPerformanceService.deleteContractPerformance(ctid);
		return JSON.toJSONString(0);
	}
	
	
	
	/**
	 * 删除合同文件
	 * */
	@RequestMapping(value="/customer/deletecontractfile")
	@ResponseBody
	public String deleteContractFile(String fileid,String uid,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		//先判断uid是否符合规则（是自己的 或者  管理员的）
		if (uid == null || uid == "") {
			return JSON.toJSONString(0);
		} 
		if (Long.parseLong(uid) != getLoginUser().getId()) {
			return JSON.toJSONString(0);
		}
		//管理员的帐号暂时没加判断
		
		//根据fileid获取记录，删除记录（设置isdel = 1）
		ContractFiles cf = new ContractFiles();
		cf.setFileid(Long.parseLong(fileid));
		cf = contractFilesService.getContractFilesByFileId(Long.parseLong(fileid));
		cf.setIsdel(1);
		int result = contractFilesService.updataContractFiles(cf);
		return JSON.toJSONString(result);
	}
	
	/**
	 * 收款 添加收款记录
	 * */
	@RequestMapping(value="/customer/savecollectionmoneylog")
	@ResponseBody
	public String saveCollectionMoneyLog(@ModelAttribute ContractMoneylog cml,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		//收付款类型（收款）
		//cml.setType(1);
		cml.setState(0);
		cml.setCreateuser(getLoginUser().getId());
		//存入数据库
		int result = 0;
		/*
		ContractMoneylog中的paytype表示的是垫款(0)还是全款(1)，
		这里要加一个判断，要是垫款的话，看看有没有还没批准的垫款
		一个用户同一时间只能有一个垫款。
		如果以后要改，直接把下面的判断删了就行。
		*/
		/*if (cml.getPaytype() != null && cml.getPaytype()== 0) {
			//看看记录中还有没有没该用户审批的垫款
			int logcount = contractMoneylogService.selectLogCountByParams(cml);
			//大于0说明有记录，就不能给申请
			if (logcount > 0) {
				return JSON.toJSONString(3);
			}
		}*/
		try{
			result = contractMoneylogService.insertMoneyLog(cml);
			/*try{
				//在这里要加一个判断是否是第一次付款，如果是第一次付款，大喇叭播报
				int count = contractMoneylogService.selectskcount(cml);
				if (count == 1) {
					//通知群 签单成功
					Contract c = new Contract();
					c.setId(cml.getContractid());
					c =contractService.getContractInfo(c);
					CustomerInfo customer = customerService.getCustomerInfoById(c.getCusid());
					//String msg = "系统消息：恭喜"+getLoginUser().getInfo().getName()+"以"+c.getTotalamount()+"元签下"+customer.getCname();
				
					String msg = "恭喜"+getLoginUser().getInfo().getName()+"以"+c.getTotalamount()+"元签下"+customer.getCname();
					SysMessage ms = new SysMessage();
					ms.setIsread(1);
					ms.setType(2);
					ms.setContent(msg);
					ms.setCreateuser(0L);
					sysService.insertMessage(ms);
					try {
						CQSDK.sendGroupMsg(Constants.GroupNumber, "系统消息："+msg);
					}catch(Exception e) {
					}
					//Document doc = Jsoup.connect(Constants.TipServer.TipServerUrl).data("msg","系统消息：恭喜"+getLoginUser().getInfo().getName()+"以"+c.getTotalamount()+"元签下"+customer.getCname()).data("gpn",Constants.TipServer.GroupName).userAgent("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0; BIDUBrowser 2.x)").post();
				}
			}catch(Exception e){ 
			}*/
			
		}catch(Exception e){ 
			e.printStackTrace();
		}
		/*String url = "/customer/intocontractlist";
		return "redirect:" + url;*/
		return JSON.toJSONString(result);
	}
	
	/**
	 * 2017/10/12新增
	 * 添加收款记录,带收款凭证
	 * 新增了一个字段voucher 用来储存凭证文件
	 * 流程:
	 * 将上传的文件存入file表获取fileid,拼接后存入voucher
	 * 后续流程同原来的流程
	 * */
	@RequestMapping(value="/customer/saveskmoneylog")
	public String saveskmoneylog(@RequestParam MultipartFile[] file,@ModelAttribute ContractMoneylog cml,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		//保存上传的收款凭证
		List<MultipartFile> files = Arrays.asList(file);
		List<FilesInfo> list = filesInfoService.saveFile(files);
		//将fileid拼接
		String voucher = null;
		for (int i = 0; i <list.size(); i++ ) {
			if (i == 0) {
				voucher = list.get(i).getId().toString();
			} else {
				voucher = voucher + "," + list.get(i).getId().toString();
			}
		}
		
		//收付款类型（收款）
		cml.setState(0);
		cml.setCreateuser(getLoginUser().getId());
		cml.setVoucher(voucher);
		//存入数据库
		int result = 0;
		try{
			result = contractMoneylogService.insertMoneyLog(cml);
			try{
				//在这里要加一个判断是否是第一次付款，如果是第一次付款，大喇叭播报
				int count = contractMoneylogService.selectskcount(cml);
				if (count == 1) {
					//通知群 签单成功
					Contract c = new Contract();
					c.setId(cml.getContractid());
					c =contractService.getContractInfo(c);
					CustomerInfo customer = customerService.getCustomerInfoById(c.getCusid());
					String msg = "恭喜"+getLoginUser().getInfo().getName()+"以"+c.getTotalamount()+"元签下"+customer.getCname();
					
					SysMessage ms = new SysMessage();
					ms.setIsread(1);
					ms.setType(2);
					ms.setContent(msg);
					ms.setSenduser(0L);
					ms.setReceiveuser(0L);
					ms.setCreateuser(0L);
					sysService.insertMessage(ms);
					try {
						CQSDK.sendGroupMsg(Constants.GroupNumber, "系统消息："+msg);
					}catch(Exception e) {
					}
					//Document doc = Jsoup.connect(Constants.TipServer.TipServerUrl).data("msg","系统消息：恭喜"+getLoginUser().getInfo().getName()+"以"+c.getTotalamount()+"元签下"+customer.getCname()).data("gpn",Constants.TipServer.GroupName).userAgent("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0; BIDUBrowser 2.x)").post();
				}
			}catch(Exception e){
				
			}
			
		}catch(Exception e){ 
			e.printStackTrace();
		}
		
		
		
		
		return "redirect:/customer/intocontractlist";
	}
	
	
	
	
	
	
	/**
	 * 收款 付款记录列表页面   0 付款   1 收款
	 * @throws UnsupportedEncodingException 
	 * */
	@RequestMapping(value="/customer/moneyrecord", produces="text/html;charset=UTF-8")
	public String moneyrecordList(@ModelAttribute ContractMoneylog c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		/*Long pid = Long.parseLong(request.getParameter("pid"));
		Long id = c.getContractid(); */
		
		String url = "customercontract/paymentrecord";
		if(c.getType()==1){
			url = "customercontract/collectionrecord";
			//ca.setId(id);
		}
		//c.setType(0);
		//c.setCreateuser(getLoginUser().getId());
		List<ContractMoneylog>  list = contractMoneylogService.getContractMoneylogList(c, getSkipToPage(), 20);
		
		Contract ca = new Contract();
		ca.setId(c.getContractid());
		Contract  caObj = contractService.getContractInfo(ca);
		request.setAttribute("record", list); 
		request.setAttribute("info", caObj); 
		return url;	
	}
	 
	
	/**
	 * 付款详情页面
	 * @throws UnsupportedEncodingException 
	 * */
	@RequestMapping(value="/customer/paymentinfo", produces="text/html;charset=UTF-8")
	public String intoReceivablesList(@ModelAttribute ContractMoneylog c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		String url = "customercontract/paymentinfo";
		ContractMoneylog  info = contractMoneylogService.getContractMoneylogInfo(c);
		if (info.getContractInfo() != null && info.getContractInfo().getPid() != null && info.getContractInfo().getPid() > 0) {
			Long pid = info.getContractInfo().getPid() != null ? info.getContractInfo().getPid() : 0L;
			Contract ct = new Contract();
			if (pid != null && pid > 0) {
				//根据pid查企业详情
				ct.setId(pid);
				ct = contractService.getContractInfo(ct);
			} else {
				ct = null;
			}
			request.setAttribute("cinfo", ct);
		}
		/*Contract ca = new Contract();
		ca.setId(info.getContractid());
		Contract  caObj = contractService.getContractInfo(ca); */
		request.setAttribute("record", info); 
	    request.setAttribute("info", info.getContractInfo());
		return url;	
	}
	
	/**
	 * 上传合同
	 * */
	@RequestMapping(value="/customer/uploadcontractfile", produces="text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String uploadContractFile(@RequestParam MultipartFile[] file,String remark,String contractid,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		/*
		 * 很显然，要知道流程：
		 * 1保存上传的合同文件到crm_files_info
		 * 2将备注和fileid，合同id保存到crm_contract_files
		 * 3更改crm_contract中的state=7
		 * 4返回页面，页面中上传合同变为申请发票
		 * */
		Map<String,Object> map = new HashMap<String,Object>();
		//先保存合同文件
		List<MultipartFile> files = Arrays.asList(file);
		List<FilesInfo> list = filesInfoService.saveFile(files);
		//保存到crm_contract_files
		ContractFiles cf = new ContractFiles();
		cf.setContractid(Long.parseLong(contractid));
		cf.setRemark(remark);
		cf.setIsdel(0);
		int size=0;
		for (FilesInfo fi : list) {
			if (fi != null && fi.getId() != null) {
				cf.setFileid(fi.getId());
				cf = contractFilesService.insertContractFiles(cf);
				size++;
			}
		}
		Contract c = new Contract();
		c.setId(Long.parseLong(contractid));
		c = contractService.getContractInfo(c);
		//判断回款 或者付款完成后  设置合同为已上传合同文件
		if(c.getState()==Constants.ContactsState.SIX || c.getState()==Constants.ContactsState.FIVE) {
			c.setState(Constants.ContactsState.EIG);
			contractService.updateContract(c);
		} 
		map.put("size",size);
		return JSON.toJSONString(map);//"redirect:/customer/contractlisturl";
	}
	
	
	@RequestMapping(value="/customer/uploadcontractfileajax", produces="text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String uploadContractFile(@RequestParam Long[] file,String remark,String contractid,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		/*
		 * 很显然，要知道流程：
		 * 1保存上传的合同文件到crm_files_info
		 * 2将备注和fileid，合同id保存到crm_contract_files
		 * 3更改crm_contract中的state=7
		 * 4返回页面，页面中上传合同变为申请发票
		 * */
		
	   int result =0;
		//获取合同信息
		Contract c = new Contract();
		c.setId(Long.parseLong(contractid));
		c = contractService.getContractInfo(c);
		//保存到crm_contract_files
		ContractFiles cf = new ContractFiles();
		cf.setContractid(Long.parseLong(contractid));
		cf.setRemark(remark);
		cf.setIsdel(0);
		for (Long fi : file) {
			if (fi != null ) {
				cf.setFileid(fi);
				cf = contractFilesService.insertContractFiles(cf);
				result =1;
			}
		}
		//判断回款 或者付款完成后  设置合同为已上传合同文件
		if(c.getState()==Constants.ContactsState.SIX || c.getState()==Constants.ContactsState.FIVE) {
			 c.setState(Constants.ContactsState.EIG);
			 contractService.updateContract(c); 
		}
		return JSON.toJSONString(result);
	}
	
	/**
	 * 申请发票
	 * */
	@RequestMapping(value="/customer/applyforbill")
	public String applyForBill(@ModelAttribute ContractBill cb,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes)  throws Exception {
		
		/*
		 * 申请发票，设置approvalstatus审批状态为审批中
		 * 添加审批
		 * */
		cb.setCreateuser(getLoginUser().getId());
		contractBillService.insert(cb);
		
		ApproveItem ai = new ApproveItem();
		ai.setType(2);
		
		//这里先把发票设为已申请
		Contract c = new Contract();
		c.setId(cb.getContractid());
		c = contractService.getContractInfo(c);
		c.setBill(1);
		contractService.updateContract(c);
		return "redirect:/customer/contractlisturl";
	}
	
	
	
	
	
	/**
	 * 发票详情页面
	 * */
	@RequestMapping(value="/customer/billfo", produces="text/html;charset=UTF-8")
	public String intoBillPage(@ModelAttribute ContractBill c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		String url = "customercontract/billinfo";
		/*
		 * 这里还有一个要更改的，就是在查详情的时候要把审批到哪里了给查出来
		 * */
		ContractBill cb =  contractBillService.selectBillInfoByParams(c);
		
		request.setAttribute("record", cb);
		request.setAttribute("info", cb.getContractInfo());
		return url;
	}
	
	/**
	 * 根据合同id和客户id验证收付款金额有没有超标
	 * */
	@RequestMapping(value="/customer/checkisover")
	@ResponseBody
	public String checkMoneyIsOver(String id,String cusid,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		Contract c = new Contract();
		c.setId(Long.parseLong(id));
		c.setCusid(Long.parseLong(cusid));
		//查询是否超出总金额
		boolean b = contractService.checkMoneyIsOver(c);
		if (b) {
			return JSON.toJSONString(0);
		} else {
			return JSON.toJSONString(1);
		}
	}
	
	/**
	 * 根据输入的关键字,查询银行名称
	 * */
	@RequestMapping(value="/customer/selectbankname",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String selectBankName(String key,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		ContractMoneylog cml = new ContractMoneylog();
		cml.setKeyWord(key);
		List<ContractMoneylog> list = contractMoneylogService.selectBnakName(cml);
		return JSON.toJSONString(list);
	}
	
	
	/**
	 * 修改合同选择页面
	 * */
	@RequestMapping(value="/customer/updatecon")
	public String updateContact(@ModelAttribute Contract c,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		//这里要加个判断,是个人合同还是企业合同,如果是企业合同,可以修改合同内容和回款记录,如果是个人合同,直接跳转到
		
		if (c.getType() == 1) {
			//企业
			Contract result = contractService.getContractInfo(c);
			//所以我要先知道合同的id
			Long contractid = result.getId();
			List<ContractFiles> fileList = contractFilesService.getFileIdByConid(contractid);
			result.setFileList(fileList);
			//然后还有人才证书合同列表
			Contract ca = new Contract();
			ca.setPid(contractid);
			List<Contract>  sublist = contractService.getAllContractListByPid(ca);
			for (Contract ct : sublist) {
				ct.setFileList(contractFilesService.getFileIdByConid(ct.getId()));
			}
			result.setSublist(sublist);
			request.setAttribute("info", result);
			
			return "customercontract/updatecontract";
		} else {
			//个人
			ContractMoneylog cml = new ContractMoneylog();
			cml.setContractid(c.getId());
			List<ContractMoneylog>  list = contractMoneylogService.getContractMoneylogList(cml, null, null);
			
			Contract co = new Contract();
			co.setId(c.getPid());
			co = contractService.getContractInfo(co);
			
			request.setAttribute("record", list); 
			request.setAttribute("info", co);
		
			return "customercontract/updatepaymoney";
		}
		
	}
	
/*	public String saveContract(@ModelAttribute Contract c,@RequestParam("cids") Long cids[],@RequestParam("totalms") Integer totalms[],
			@RequestParam("alonems") Integer alonems[],@RequestParam("uids") Long uids[],@RequestParam("otmoney") Integer otmoney[],@RequestParam("advancemoney") Integer advancemoney[],@RequestParam("zsremark") String zsremark[], 
			HttpServletResponse response,HttpServletRequest request,RedirectAttributes redirectAttributes){*/
		
	/**
	 * 保存合同修改
	 * */
	@RequestMapping(value="/customer/savecontentupdate")
	@ResponseBody
	public String saveContentUpdate(@ModelAttribute Contract c,@RequestParam("cids") Long cids[],@RequestParam("totalms") Integer totalms[],
			@RequestParam("alonems") Integer alonems[],@RequestParam("uids") Long uids[],@RequestParam("otmoney") Integer otmoney[],@RequestParam("advancemoney") Integer advancemoney[],@RequestParam("zsremark") String zsremark[], 
			HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		//人才中的pid是对应企业的id
		int result = 0; //失败
		//将获取的数据存入合同对象中
		if(c!=null&&cids!=null&&totalms!=null&&uids!=null){
			c.setUid(getLoginUser().getId());
			c.setCreateuser(c.getUid());
			List<Contract>  sublist = new ArrayList();
			int i = 0;
			for(Long cid:cids){
				Contract  newContract = new Contract();
				newContract.setUid(uids[i]);
				newContract.setCusid(cid);
				newContract.setSigningtime(c.getSigningtime());
				newContract.setLifetype(c.getLifetype());
				newContract.setTotalamount(totalms[i]);
				newContract.setAlonemoney(alonems[i]);
				newContract.setCreateuser(c.getUid());
				newContract.setAdvancemoney(advancemoney[i]);
				newContract.setOthermoney(otmoney[i]);
				if(zsremark!=null&&zsremark.length>0) {
					newContract.setZsremark(zsremark[i]);
				} 
				sublist.add(newContract);
				if(newContract.getOthermoney()!=null&&newContract.getOthermoney()>0){
					Contract  newContractOne = new Contract();
					newContractOne.setUid(uids[i]);
					newContractOne.setCusid(cid);
					newContractOne.setSigningtime(c.getSigningtime());
					newContractOne.setLifetype(c.getLifetype());
					newContractOne.setTotalamount(otmoney[i]);
					newContractOne.setAlonemoney(otmoney[i]);
					newContractOne.setCreateuser(c.getUid());
					newContractOne.setOthermoney(0);
					newContractOne.setIsadditional(1);
					newContractOne.setZsremark("");
					sublist.add(newContractOne);
					
				}
				i++;
			}
			c.setSublist(sublist);
			
			//创建合同修改记录对象
			ContractUpdateHistory cuh = new ContractUpdateHistory();
			cuh.setIsdel(0);
			cuh.setType(1); //合同
			cuh.setContractid(c.getId()); //合同id
			cuh.setAppstate(0);
			cuh.setContent(JSON.toJSONString(c)); //将对象转换成json格式存入数据库
			cuh.setCreateuser(getLoginUser().getId());
			cuh.setCreateuserName(getLoginUser().getInfo().getName());
			
			result = contractUpdateHistoryService.insertHistyoryAndApprove(cuh);
			
		}
		
		return JSON.toJSONString(result);
	}
	
	
	/**
	 * 根据id获取收付款详情
	 * */
	@RequestMapping(value="/customer/getmoneylogbyid",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getMoneyLogByid(@ModelAttribute ContractMoneylog cml,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		ContractMoneylog info = contractMoneylogService.getContractMoneylogInfo(cml);
		
		return JSON.toJSONString(info);
	}
	
	/**
	 * 保存收款修改
	 * */
	@RequestMapping(value="/customer/upskmoneylog")
	public String saveUpSkMoneyLog(@RequestParam MultipartFile[] file,@ModelAttribute ContractMoneylog cml,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception{
		
		//保存上传的收款凭证
		List<MultipartFile> files = Arrays.asList(file);
		List<FilesInfo> list = filesInfoService.saveFile(files);
		//将fileid拼接
		String voucher = null;
		for (int i = 0; i <list.size(); i++ ) {
			if (i == 0) {
				voucher = list.get(i).getId().toString();
			} else {
				voucher = voucher + "," + list.get(i).getId().toString();
			}
		}
		
		//收付款类型（收款）
		cml.setState(0);
		cml.setCreateuser(getLoginUser().getId());
		cml.setVoucher(voucher);
		
		//创建合同修改记录对象
		ContractUpdateHistory cuh = new ContractUpdateHistory();
		cuh.setIsdel(0);
		cuh.setType(2); //收款
		cuh.setContentid(cml.getId());
		cuh.setAppstate(0);
		cuh.setContent(JSON.toJSONString(cml)); //将对象转换成json格式存入数据库
		cuh.setCreateuser(getLoginUser().getId());
		cuh.setCreateuserName(getLoginUser().getInfo().getName());
		
		contractUpdateHistoryService.insertHistyoryAndApprove(cuh);
		
		return "redirect:/customer/intocontractlist";
	}
	
	
	/**
	 * ajax获取付款记录
	 * */
	@RequestMapping(value="/customer/ajaxgetpaymoney",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getPayMoneyList(@ModelAttribute ContractMoneylog cml,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		cml = contractMoneylogService.getContractMoneylogInfo(cml);
		return JSON.toJSONString(cml);
	}
	
	
	/**
	 * 保存付款修改
	 * */
	@RequestMapping(value="/customer/upfkmoneylog")
	@ResponseBody
	public String upfkMoneyLog(@ModelAttribute ContractMoneylog cml,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception {
		
		//收付款类型（付款）
		cml.setState(0);
		cml.setCreateuser(getLoginUser().getId());
		
		//创建合同修改记录对象
		ContractUpdateHistory cuh = new ContractUpdateHistory();
		cuh.setIsdel(0);
		cuh.setType(3);
		cuh.setContentid(cml.getId());
		cuh.setAppstate(0);
		cuh.setContent(JSON.toJSONString(cml)); //将对象转换成json格式存入数据库
		cuh.setCreateuser(getLoginUser().getId());
		cuh.setCreateuserName(getLoginUser().getInfo().getName());
		int result = contractUpdateHistoryService.insertHistyoryAndApprove(cuh);
		return JSON.toJSONString(result);
	}
	
	
	
	
	/**
	 * 审批查看的页面
	 * ApproveItemUserMapper.selectApproveUserByFkid
	 * */
	@RequestMapping(value="/customer/contractuphistoryInfo")
	public String contractUpHistoryInfo(@ModelAttribute ContractUpdateHistory cuh,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		cuh = contractUpdateHistoryService.getCUHByParams(cuh);
		
		Contract c = null;
		ContractMoneylog cml = null;
		
		ApproveItem ai = new ApproveItem();
		ai.setType(4);
		ai.setFkid(cuh.getId());
		List<ApproveItemUser> list = approveItemService.selectApproveUserByFkid(ai);
		cuh.setApproveUser(list);
		
		//在这里判断是什么类型的修改
		if (cuh != null) {
			if (cuh.getType() == 1) {
				//1合同
				c = JSON.parseObject(cuh.getContent(), Contract.class);
				for (Contract sc : c.getSublist()) {
					sc.setCustomerInfo(customerService.getCustomerInfoById(sc.getCusid()));
					sc.setCreateuserName(userService.getUserInfo(sc.getUid()).getName());
				}
				
			} else if (cuh.getType() == 2) {
				//2收款
				cml = JSON.parseObject(cuh.getContent(), ContractMoneylog.class);
				
			} else {
				//3付款
				cml = JSON.parseObject(cuh.getContent(), ContractMoneylog.class);
			}
		}
		
		request.setAttribute("contract", c);
		request.setAttribute("moneylog", cml);
		request.setAttribute("cuh", cuh);
		
		return "customercontract/upcontractapprove";
	}
	
	/**
	 * 检查是否有审批中的记录
	 * 根据type判断传回来的是合同id还是moneylog的id
	 * */
	@RequestMapping(value="/customer/checkhistoryisexist")
	@ResponseBody
	public String checkHistoryIsExist(String type,String id,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		ContractUpdateHistory cuh = new ContractUpdateHistory();
		
		if (Integer.parseInt(type) == 1) {
			//说明是合同
			cuh.setContractid(Long.parseLong(id));
		} else {
			//说明是moneylog
			cuh.setContentid(Long.parseLong(id));
		}
		int result = contractUpdateHistoryService.checkHistoryIsExist(cuh);
		
		return JSON.toJSONString(result);
	}
	

}
